package com.ensentec.Lib;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

/**
 * Created by ztlchina on 17-7-28.
 * 打印机控制相关类
 */

public class Printer {
    private static Printer ourInstance;

    public static Printer getInstance() {
        if (null == ourInstance)
        {
            ourInstance = new Printer();
            ourInstance.onCreate();
        }
        return ourInstance;
    }

    private String TAG = Printer.class.getSimpleName();
    private SerialPort mSerialPort;
    private OutputStream mOutputStream;
    private InputStream mInputStream;
    //private ReadThread mReadThread;
    private String path = "/dev/ttySAC1";
    private int baudrate = 115200;
    private int stop = 1;
    private int bits = 8;
    private byte even = 0x03;   //3: 无校验
    private int block = 1;

    /**
     * 初始化串口信息
     */
    public void onCreate() {
        try {
            mSerialPort = new SerialPort(new File(path), baudrate, bits, even, stop, block);
            mOutputStream = mSerialPort.getOutputStream();
            mInputStream = mSerialPort.getInputStream();

//            mReadThread = new ReadThread();
//            isStop = false;
//            mReadThread.start();
        } catch (Exception e) {
            e.printStackTrace();
        }
        //initBle();
    }

    /**
     * 发送指令到串口
     *
     * @param cmd
     * @return
     */
    public boolean sendCmds(String cmd,String no) {
        boolean result = true;
        byte[] mBuffer = (cmd+"\r\n").getBytes();

        try {
            if (mOutputStream != null) {
                mOutputStream.write(mBuffer);
            } else {
                result = false;
            }
        } catch (IOException e) {
            e.printStackTrace();
            result = false;
        }
        return result;
    }

    /**
     * 关闭串口
     */
    public void closeSerialPort() {
//        isStop = true;
//        if (mReadThread != null) {
//            mReadThread.interrupt();
//        }
        if (mSerialPort != null) {
            mSerialPort.close();
        }
    }
}
